/**
 * 云函数环境下的种子数据导入脚本
 * 适用于云函数云端测试环境
 * 使用方式：在云函数控制台直接调用此函数
 */
const cloud = require('wx-server-sdk');
const config = require('../config/config.js');

// 内嵌种子数据
const SEED_DATA = {
  ax_admin: [
    {
      "_pid": "A00",
      "ADMIN_ID": "admin_super",
      "ADMIN_NAME": "超级管理员",
      "ADMIN_PHONE": "13800000000",
      "ADMIN_STATUS": 1,
      "ADMIN_LOGIN_CNT": 0,
      "ADMIN_LOGIN_TIME": 0,
      "ADMIN_TYPE": 1,
      "ADMIN_TOKEN": "",
      "ADMIN_TOKEN_TIME": 0,
      "linkedUserId": "oTEST_OPENID_SUPER",
      "linkedStoreIds": [],
      "permissions": { "all": true },
      "lastLoginDevice": "",
      "isActive": true,
      "role": "super_admin",
      "description": "系统初始化超级管理员",
      "ADMIN_ADD_TIME": 0,
      "ADMIN_EDIT_TIME": 0,
      "ADMIN_ADD_IP": "",
      "ADMIN_EDIT_IP": ""
    },
    {
      "_pid": "A00",
      "ADMIN_ID": "admin_normal",
      "ADMIN_NAME": "门店管理员",
      "ADMIN_PHONE": "13900000000",
      "ADMIN_STATUS": 1,
      "ADMIN_LOGIN_CNT": 0,
      "ADMIN_LOGIN_TIME": 0,
      "ADMIN_TYPE": 0,
      "ADMIN_TOKEN": "",
      "ADMIN_TOKEN_TIME": 0,
      "linkedUserId": "oTEST_OPENID_NORMAL",
      "linkedStoreIds": ["store_001"],
      "permissions": { "stores": ["store_001"], "device": true, "order": true },
      "lastLoginDevice": "",
      "isActive": true,
      "role": "admin",
      "description": "系统初始化门店管理员",
      "ADMIN_ADD_TIME": 0,
      "ADMIN_EDIT_TIME": 0,
      "ADMIN_ADD_IP": "",
      "ADMIN_EDIT_IP": ""
    }
  ],
  
  ax_stores: [
    {
      "_pid": "A00",
      "_id": "store_001",
      "storeId": "store_001",
      "name": "超级泡泡蓝光宠物店(旗舰店)",
      "address": "福建省福州市晋安区鼓山镇前横北路蓝光星珀9#19",
      "location": { "latitude": 26.0745, "longitude": 119.3649 },
      "phone": "18558880680",
      "openingHours": "周一至周日 09:00-21:00",
      "coverImage": "cloud://CLOUD_ID/store_001_cover.jpg",
      "doorLockId": "doorlock_store_001",
      "status": 1,
      "createTime": 0,
      "updateTime": 0
    }
  ],
  
  ax_services: [
    {
      "_pid": "A00",
      "storeIds": ["store_001"],
      "name": "自助洗浴",
      "serviceType": "bath",
      "description": "提供自助宠物洗浴服务，支持智能设备、恒温水温、安全防护",
      "price": 6800,
      "duration": 30,
      "roomType": "",
      "quantity": 1,
      "unit": "次",
      "status": 1,
      "createTime": 0,
      "updateTime": 0
    },
    {
      "_pid": "A00",
      "storeIds": ["store_001"],
      "name": "寄养(单间)",
      "serviceType": "foster",
      "description": "提供温馨单间寄养服务，含每日巡视两次、定时喂食",
      "price": 8800,
      "duration": 1440,
      "roomType": "single",
      "quantity": 1,
      "unit": "天",
      "status": 1,
      "createTime": 0,
      "updateTime": 0
    }
  ],
  
  ax_employees: [
    {
      "_pid": "A00",
      "_id": "emp_001",
      "storeId": "store_001",
      "name": "王小美",
      "title": "宠物美容师",
      "tags": ["洗护", "造型"],
      "avatar": "cloud://CLOUD_ID/avatars/emp_001.jpg",
      "status": 1,
      "createTime": 0,
      "updateTime": 0
    },
    {
      "_pid": "A00",
      "_id": "emp_002",
      "storeId": "store_001",
      "name": "李师傅",
      "title": "宠物护理师",
      "tags": ["寄养照护", "健康观察"],
      "avatar": "cloud://CLOUD_ID/avatars/emp_002.jpg",
      "status": 1,
      "createTime": 0,
      "updateTime": 0
    }
  ],
  
  ax_devices: [
    {
      "_pid": "A00",
      "_id": "device_pool_mid",
      "storeId": "store_001",
      "name": "中池",
      "status": 1,
      "remainingTime": 0,
      "currentOrderId": "",
      "lastUpdateTime": 0,
      "endTime": 0,
      "type": "bath",
      "code": "POOL-MID",
      "iotId": "iot_pool_mid",
      "category": "洗浴",
      "location": "一楼洗护区-中间区域",
      "price": 6800,
      "publishTopic": "/CPHgXm/sfosIpzgovLI/8cce4e519eea/publish",
      "subscribeTopics": "/CPHgXm/sfosIpzgovLI/8cce4e519eea/subscribe",
      "isOnline": true,
      "switchStatus": false,
      "currentTemperature": 25.0,
      "waterLevel": 80,
      "createTime": 0,
      "updateTime": 0
    },
    {
      "_pid": "A00",
      "_id": "device_access",
      "storeId": "store_001",
      "name": "门禁",
      "status": 1,
      "remainingTime": 0,
      "currentOrderId": "",
      "lastUpdateTime": 0,
      "endTime": 0,
      "type": "access_control",
      "code": "ACCESS-001",
      "iotId": "iot_access_001",
      "category": "门禁",
      "location": "门口-入口处",
      "price": 0,
      "publishTopic": "/CPHgXm/kHKxitSJhWTz/8cce4e518bf9/publish",
      "subscribeTopics": "/CPHgXm/kHKxitSJhWTz/8cce4e518bf9/subscribe",
      "isOnline": true,
      "switchStatus": false,
      "currentTemperature": 0,
      "waterLevel": 0,
      "createTime": 0,
      "updateTime": 0
    },
    {
      "_pid": "A00",
      "_id": "device_pool_big",
      "storeId": "store_001",
      "name": "大池",
      "status": 1,
      "remainingTime": 0,
      "currentOrderId": "",
      "lastUpdateTime": 0,
      "endTime": 0,
      "type": "bath",
      "code": "POOL-BIG",
      "iotId": "iot_pool_big",
      "category": "洗浴",
      "location": "一楼洗护区-靠里侧",
      "price": 8800,
      "publishTopic": "/CPHgXm/EfSrgqEVMzVy/8cce4e519efd/publish",
      "subscribeTopics": "/CPHgXm/EfSrgqEVMzVy/8cce4e519efd/subscribe",
      "isOnline": true,
      "switchStatus": false,
      "currentTemperature": 25.0,
      "waterLevel": 80,
      "createTime": 0,
      "updateTime": 0
    },
    {
      "_pid": "A00",
      "_id": "device_dryer_small_a",
      "storeId": "store_001",
      "name": "小烘干箱A（左边）",
      "status": 1,
      "remainingTime": 0,
      "currentOrderId": "",
      "lastUpdateTime": 0,
      "endTime": 0,
      "type": "dry",
      "code": "DRY-SMALL-A",
      "iotId": "iot_dryer_small_a",
      "category": "烘干",
      "location": "一楼烘干区-左侧",
      "price": 5800,
      "publishTopic": "/CPHgXm/zHFdQWsCfUvH/8cce4e518b8c/publish",
      "subscribeTopics": "/CPHgXm/zHFdQWsCfUvH/8cce4e518b8c/subscribe",
      "isOnline": true,
      "switchStatus": false,
      "currentTemperature": 0,
      "waterLevel": 0,
      "createTime": 0,
      "updateTime": 0
    },
    {
      "_pid": "A00",
      "_id": "device_dryer_small_b",
      "storeId": "store_001",
      "name": "小烘干箱B（右边）",
      "status": 1,
      "remainingTime": 0,
      "currentOrderId": "",
      "lastUpdateTime": 0,
      "endTime": 0,
      "type": "dry",
      "code": "DRY-SMALL-B",
      "iotId": "iot_dryer_small_b",
      "category": "烘干",
      "location": "一楼烘干区-右侧",
      "price": 5800,
      "publishTopic": "/CPHgXm/YYuHFGSGudTL/8cce4e519fef/publish",
      "subscribeTopics": "/CPHgXm/YYuHFGSGudTL/8cce4e519fef/subscribe",
      "isOnline": true,
      "switchStatus": false,
      "currentTemperature": 0,
      "waterLevel": 0,
      "createTime": 0,
      "updateTime": 0
    },
    {
      "_pid": "A00",
      "_id": "device_dryer_big",
      "storeId": "store_001",
      "name": "大烘干箱",
      "status": 1,
      "remainingTime": 0,
      "currentOrderId": "",
      "lastUpdateTime": 0,
      "endTime": 0,
      "type": "dry",
      "code": "DRY-BIG",
      "iotId": "iot_dryer_big",
      "category": "烘干",
      "location": "一楼烘干区-中间",
      "price": 6800,
      "publishTopic": "/CPHgXm/yRtLOTpYLDwJ/8cce4e518b96/publish",
      "subscribeTopics": "/CPHgXm/yRtLOTpYLDwJ/8cce4e518b96/subscribe",
      "isOnline": true,
      "switchStatus": false,
      "currentTemperature": 0,
      "waterLevel": 0,
      "createTime": 0,
      "updateTime": 0
    },
    {
      "_pid": "A00",
      "_id": "device_blower",
      "storeId": "store_001",
      "name": "吹水机",
      "status": 1,
      "remainingTime": 0,
      "currentOrderId": "",
      "lastUpdateTime": 0,
      "endTime": 0,
      "type": "blow",
      "code": "BLOW-001",
      "iotId": "iot_blow_001",
      "category": "吹水",
      "location": "一楼洗护区-靠近洗浴区",
      "price": 3000,
      "publishTopic": "/CPHgXm/kUUjbOpBxdTC/8cce4e518aa8/publish",
      "subscribeTopics": "/CPHgXm/kUUjbOpBxdTC/8cce4e518aa8/subscribe",
      "isOnline": true,
      "switchStatus": false,
      "currentTemperature": 0,
      "waterLevel": 0,
      "createTime": 0,
      "updateTime": 0
    },
    {
      "_pid": "A00",
      "_id": "device_pool_small",
      "storeId": "store_001",
      "name": "小池",
      "status": 1,
      "remainingTime": 0,
      "currentOrderId": "",
      "lastUpdateTime": 0,
      "endTime": 0,
      "type": "bath",
      "code": "POOL-SMALL",
      "iotId": "iot_pool_small",
      "category": "洗浴",
      "location": "一楼洗护区-靠近门口",
      "price": 5800,
      "publishTopic": "/CPHgXm/cyeYtbDVScOw/8cce4e518cca/publish",
      "subscribeTopics": "/CPHgXm/cyeYtbDVScOw/8cce4e518cca/subscribe",
      "isOnline": true,
      "switchStatus": false,
      "currentTemperature": 25.0,
      "waterLevel": 80,
      "createTime": 0,
      "updateTime": 0
    }
  ],
  
  ax_news: [
    {
      "_pid": "A00",
      "NEWS_ID": "news_001",
      "NEWS_ADMIN_ID": "admin_super",
      "NEWS_TYPE": 0,
      "NEWS_TITLE": "欢迎来到超级泡泡蓝光宠物店",
      "NEWS_DESC": "我们为您和爱宠提供专业、贴心的一站式服务。",
      "NEWS_URL": "",
      "NEWS_STATUS": 1,
      "NEWS_CATE_ID": "0",
      "NEWS_CATE_NAME": "公告",
      "NEWS_ORDER": 1,
      "NEWS_HOME": 1,
      "NEWS_CONTENT": "本店提供自助洗浴、寄养、护理等多项服务，欢迎体验！",
      "NEWS_VIEW_CNT": 0,
      "NEWS_FAV_CNT": 0,
      "NEWS_COMMENT_CNT": 0,
      "NEWS_LIKE_CNT": 0,
      "NEWS_PIC": ["cloud://CLOUD_ID/news/news_001.jpg"],
      "NEWS_ADD_TIME": 0,
      "NEWS_EDIT_TIME": 0,
      "NEWS_ADD_IP": "",
      "NEWS_EDIT_IP": ""
    }
  ],
  
  ax_recharge_packages: [
    {
      "_pid": "A00",
      "name": "基础充值包",
      "amount": 10000,
      "bonus": 1000,
      "totalAmount": 11000,
      "isRecommended": false,
      "label": "入门",
      "description": "充100送10，适合轻度使用",
      "status": 1,
      "createTime": 0,
      "updateTime": 0
    },
    {
      "_pid": "A00",
      "name": "畅享充值包",
      "amount": 30000,
      "bonus": 6000,
      "totalAmount": 36000,
      "isRecommended": true,
      "label": "推荐",
      "description": "充300送60，热门套餐",
      "status": 1,
      "createTime": 0,
      "updateTime": 0
    },
    {
      "_pid": "A00",
      "name": "尊享充值包",
      "amount": 50000,
      "bonus": 12000,
      "totalAmount": 62000,
      "isRecommended": false,
      "label": "高频使用",
      "description": "充500送120，适合重度使用",
      "status": 1,
      "createTime": 0,
      "updateTime": 0
    },
    {
      "_pid": "A00",
      "name": "尊享充值包",
      "amount": 50000,
      "bonus": 12000,
      "totalAmount": 62000,
      "isRecommended": false,
      "label": "高频使用",
      "description": "充500送120，适合重度使用",
      "status": 1,
      "createTime": 0,
      "updateTime": 0
    }
  ],
  
  ax_user_coupons: [
    {
      "_pid": "A00",
      "userId": "user_test_001",
      "couponTemplateId": "tpl_10_off",
      "couponName": "满50减10元",
      "couponType": 1,
      "discountAmount": 1000,
      "minAmount": 5000,
      "storeId": "store_001",
      "status": 1,
      "usedTime": 0,
      "usedAppointmentId": "",
      "expireTime": 0,
      "createTime": 0,
      "updateTime": 0
    },
    {
      "_pid": "A00",
      "userId": "user_test_002",
      "couponTemplateId": "tpl_20_percent",
      "couponName": "寄养服务8折",
      "couponType": 2,
      "discountAmount": null,
      "discountRate": 0.8,
      "minAmount": 0,
      "storeId": "store_001",
      "status": 1,
      "usedTime": 0,
      "usedAppointmentId": "",
      "expireTime": 0,
      "createTime": 0,
      "updateTime": 0
    }
  ],
  
  ax_foster_rooms: [
    {
      "_pid": "A00",
      "_id": "room_001",
      "roomId": "1",
      "roomName": "小寄养间",
      "roomType": "small",
      "size": "2.5m x 2m",
      "capacity": 1,
      "price": 5800,
      "unit": "天",
      "description": "适合小型犬，经济实惠，基础设施完善",
      "images": ["cloud://CLOUD_ID/rooms/room_small_1.jpg"],
      "amenities": ["恒温空调", "独立饮水", "监控摄像头"],
      "careInstructions": "每日巡视两次；定时喂食",
      "storeId": "store_001",
      "status": 1,
      "isOccupied": false,
      "currentPets": [],
      "createTime": 0,
      "updateTime": 0
    },
    {
      "_pid": "A00",
      "_id": "room_002",
      "roomId": "2",
      "roomName": "中寄养间",
      "roomType": "medium",
      "size": "3m x 2.5m",
      "capacity": 1,
      "price": 7800,
      "unit": "天",
      "description": "适合中型犬，空间适中，舒适温馨",
      "images": ["cloud://CLOUD_ID/rooms/room_medium_1.jpg"],
      "amenities": ["智能空气净化", "独立饮水", "监控摄像头", "玩具区域"],
      "careInstructions": "每日巡视三次；定时喂食；适量运动",
      "storeId": "store_001",
      "status": 1,
      "isOccupied": false,
      "currentPets": [],
      "createTime": 0,
      "updateTime": 0
    },
    {
      "_pid": "A00",
      "_id": "room_003",
      "roomId": "3",
      "roomName": "大寄养间",
      "roomType": "large",
      "size": "4m x 3m",
      "capacity": 2,
      "price": 9800,
      "unit": "天",
      "description": "适合大型犬或多只宠物，宽敞舒适，设施齐全",
      "images": ["cloud://CLOUD_ID/rooms/room_large_1.jpg"],
      "amenities": ["智能空气净化", "独立饮水", "监控摄像头", "玩具区域", "休息区"],
      "careInstructions": "每日巡视三次；定时喂食；每日户外活动",
      "storeId": "store_001",
      "status": 1,
      "isOccupied": false,
      "currentPets": [],
      "createTime": 0,
      "updateTime": 0
    },
    {
      "_pid": "A00",
      "_id": "room_004",
      "roomId": "4",
      "roomName": "临时小",
      "roomType": "temp_small",
      "size": "2m x 1.5m",
      "capacity": 1,
      "price": 500,
      "unit": "小时",
      "description": "临时寄养小间，适合短时间寄养小型犬",
      "images": ["cloud://CLOUD_ID/rooms/room_temp_small_1.jpg"],
      "amenities": ["基础通风", "饮水设施"],
      "careInstructions": "每小时巡视一次",
      "storeId": "store_001",
      "status": 1,
      "isOccupied": false,
      "currentPets": [],
      "createTime": 0,
      "updateTime": 0
    },
    {
      "_pid": "A00",
      "_id": "room_005",
      "roomId": "5",
      "roomName": "临时中",
      "roomType": "temp_medium",
      "size": "2.5m x 2m",
      "capacity": 1,
      "price": 1000,
      "unit": "小时",
      "description": "临时寄养中间，适合短时间寄养中型犬",
      "images": ["cloud://CLOUD_ID/rooms/room_temp_medium_1.jpg"],
      "amenities": ["基础通风", "饮水设施", "简易休息垫"],
      "careInstructions": "每小时巡视一次；注意宠物状态",
      "storeId": "store_001",
      "status": 1,
      "isOccupied": false,
      "currentPets": [],
      "createTime": 0,
      "updateTime": 0
    },
    {
      "_pid": "A00",
      "_id": "room_006",
      "roomId": "6",
      "roomName": "临时大",
      "roomType": "temp_large",
      "size": "3m x 2.5m",
      "capacity": 2,
      "price": 1500,
      "unit": "小时",
      "description": "临时寄养大间，适合短时间寄养大型犬或多只宠物",
      "images": ["cloud://CLOUD_ID/rooms/room_temp_large_1.jpg"],
      "amenities": ["基础通风", "饮水设施", "简易休息垫", "活动空间"],
      "careInstructions": "每小时巡视一次；确保宠物安全和舒适",
      "storeId": "store_001",
      "status": 1,
      "isOccupied": false,
      "currentPets": [],
      "createTime": 0,
      "updateTime": 0
    }
  ]
};

function getCollectionsFromConfig() {
  const raw = config.COLLECTION_NAME || '';
  return raw.split('|').map(s => s.trim()).filter(Boolean);
}

function initCloud() {
  // 云函数环境下直接初始化，无需凭证
  cloud.init({ env: config.CLOUD_ID });
  console.log('[INFO] 云函数环境初始化完成');
  return cloud;
}

async function ensureCollection(db, name) {
  try {
    await db.createCollection(name);
    console.log(`[OK] 创建集合成功: ${name}`);
  } catch (err) {
    const msg = (err && err.message) || String(err);
    if (msg.includes('exists') || msg.includes('ResourceExists') || msg.includes('already exist')) {
      console.log(`[INFO] 集合已存在: ${name}`);
    } else {
      console.warn(`[WARN] 创建集合失败: ${name} -> ${msg}`);
    }
  }
}

function normalizeDocs(json) {
  if (Array.isArray(json)) return json;
  if (json && typeof json === 'object') return [json];
  return [];
}

async function importOneCollection(db, collectionName, data) {
  const docs = normalizeDocs(data);
  if (!docs.length) {
    console.warn(`[WARN] 空数据，跳过: ${collectionName}`);
    return { collection: collectionName, success: 0, failed: 0 };
  }

  await ensureCollection(db, collectionName);

  let success = 0;
  let failed = 0;

  for (const doc of docs) {
    try {
      const { _id, ...dataWithoutId } = doc || {};
      if (_id) {
        await db.collection(collectionName).doc(_id).set({ data: dataWithoutId });
      } else {
        await db.collection(collectionName).add({ data: dataWithoutId });
      }
      success++;
    } catch (err) {
      failed++;
      const msg = (err && err.message) || String(err);
      console.error(`[ERR] 导入失败: ${collectionName} doc ${doc._id || '(no _id)'} -> ${msg}`);
    }
  }

  console.log(`[OK] 导入完成: ${collectionName} | 成功: ${success} 失败: ${failed}`);
  return { collection: collectionName, success, failed };
}

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    const cloudInstance = initCloud();
    const db = cloudInstance.database();
    const collectionsInConfig = new Set(getCollectionsFromConfig());

    // 仅导入配置中存在的集合
    const availableCollections = Object.keys(SEED_DATA);
    const targets = availableCollections.filter(name => collectionsInConfig.has(name));
    const skipTargets = availableCollections.filter(name => !collectionsInConfig.has(name));
    
    if (skipTargets.length) {
      console.log('[INFO] 以下集合未在配置中，跳过：', skipTargets.join(', '));
    }
    console.log('开始导入集合：', targets.join(', '));

    const results = [];
    for (const collectionName of targets) {
      const res = await importOneCollection(db, collectionName, SEED_DATA[collectionName]);
      results.push(res);
    }

    const summary = results.reduce((acc, r) => {
      acc.success += r.success; 
      acc.failed += r.failed; 
      return acc;
    }, { success: 0, failed: 0 });
    
    console.log('导入完成汇总：', summary);
    
    return {
      success: true,
      message: '种子数据导入完成',
      summary: summary,
      details: results
    };
  } catch (err) {
    console.error('导入脚本执行失败：', err);
    return {
      success: false,
      message: '种子数据导入失败',
      error: err.message || String(err)
    };
  }
};

// 兼容本地测试
if (require.main === module) {
  exports.main({}, {}).then(result => {
    console.log('执行结果：', result);
  }).catch(err => {
    console.error('执行失败：', err);
    process.exit(1);
  });
}